import { existsSync, readdirSync, statSync, unlinkSync, rmdirSync } from "fs";
import path, { join } from "path";

/** 删除目录下的文件,不包含子目录; ignores 忽略的文件列表 */
export function delFiles(dirPath: string, ignores?: string[]) {
    if (!existsSync(join(dirPath))) {
        console.log('no such dir');
        return;
    }
    let files = readdirSync(dirPath)
    for (const ifile of files) {
        let ifurl = join(dirPath, ifile);
        if (statSync(ifurl).isFile()) {
            // console.log(isIgnoreFile(ifurl, this.ignores), '要忽略ma');
            if (isIgnore(ifurl, ignores)) {
                continue;
            }
        }
        unlinkSync(ifurl);
    }
}

function isIgnore(url: string, ignore?: string[]) {
    return ignore.filter(ig => url.indexOf(ig) >= 0).length > 0
}

/** 删除目录，不忽略任何文件 */
export function delDir(dirPath: string) {
    if (!existsSync(dirPath)) return;
    try {
        let stat = statSync(dirPath)
        if (stat.isDirectory()) {
            let files = readdirSync(dirPath);
            files.forEach(f => {
                let ifurl = path.join(dirPath, f)
                if (statSync(ifurl).isDirectory()) {
                    delDir(ifurl);
                } else {
                    unlinkSync(ifurl);
                }
            })
            rmdirSync(dirPath);
        } else if (stat.isFile()) {
            unlinkSync(dirPath);
        }
    } catch (e) {
        console.log(e)
    }
}